unit RecentFileListManager;

interface
uses Generics.Collections,SysUtils,IniFiles;

type TRecentFileListManager=class
  private const
    RecentFilesSection:string='RecentFiles';
  private
    FMaxFileCount:integer;
    FFiles:TList<string>;
  public
    property MaxFileCount:integer read FMaxFileCount write FMaxFileCount;
    property Files:TList<string> read FFiles write FFiles;

    constructor Create;
    destructor Destroy;override;

    procedure AddFileName(fileName:string);
    procedure AppendFileName(fileName:string);
    procedure RemoveFileName(fileName:string);

    procedure SaveConfig(const IniFile:TIniFile);
    procedure LoadConfig(const IniFile:TIniFile);
end;
implementation

{ TRecentFileList }

constructor TRecentFileListManager.Create;
begin
    inherited;
    FFiles:=TList<string>.Create;
end;

destructor TRecentFileListManager.Destroy;
begin
    FFiles.Free;
    inherited;
end;

procedure TRecentFileListManager.AddFileName(fileName: string);
begin
    RemoveFileName(fileName);
    Files.Insert(0,fileName);

    while (Files.Count>MaxFileCount) and (Files.Count>0) do begin
        Files.Delete(Files.Count-1);
    end;
end;

procedure TRecentFileListManager.AppendFileName(fileName: string);
begin
    if not Files.Contains(fileName) then begin
        Files.Add(fileName);
    end;

    while (Files.Count>MaxFileCount) and (Files.Count>0) do begin
        Files.Delete(Files.Count-1);
    end;
end;

procedure TRecentFileListManager.RemoveFileName(fileName: string);
begin
    if Files.Contains(fileName) then Files.Remove(fileName);
end;

procedure TRecentFileListManager.SaveConfig(const IniFile:TIniFile);
var
    i:integer;
    keyName:string;
begin
    for i := 0 to Files.Count-1 do begin
        keyName:=IntToStr(i);
        IniFile.WriteString(RecentFilesSection,keyName,Files[i]);
    end;
end;

procedure TRecentFileListManager.LoadConfig(const IniFile: TIniFile);
var
    i:integer;
    keyName:string;
    value:string;
begin
    for i := 0 to MaxFileCount do begin
        keyName:=IntToStr(i);
        value:=IniFile.ReadString(RecentFilesSection,keyName,'');
        if FileExists(value) then begin
            AppendFileName(value);
        end else begin
            IniFile.DeleteKey(RecentFilesSection,keyName);
        end;
    end;
end;

end.
